<template>
  <div class="personal-overview">
    
    
    <!-- 推荐职位 -->
    <div class="section">
      <div class="section-header">
        <h3 class="section-title">推荐职位</h3>
        <el-button link type="primary" @click="goToJobList">
          查看更多
          <el-icon class="el-icon--right"><arrow-right /></el-icon>
        </el-button>
      </div>
      
      <el-row :gutter="20" v-loading="loading.jobs">
        <el-col :md="8" :sm="12" :xs="24" v-for="(job, index) in recommendJobs" :key="`job-${job.id || index}`">
          <el-card class="job-card" shadow="hover" @click="viewJobDetail(job.id)">
            <div class="job-header">
              <div class="job-title">{{ job.title }}</div>
              <div class="job-salary">{{ job.salary }}</div>
            </div>
            <div class="job-company">{{ job.companyName || job.company }}</div>
            <div class="job-tags">
              <el-tag v-for="(tag, i) in job.tags" :key="`tag-${i}`" size="small">
                {{ tag }}
              </el-tag>
            </div>
            <div class="job-footer">
              <span class="job-location">{{ job.city || job.location }}</span>
              <span class="job-date">{{ formatDate(job.postTime) || job.date }}</span>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="24" v-if="!loading.jobs && recommendJobs.length === 0">
          <el-empty description="暂无推荐职位" :image-size="100" />
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElLoading } from 'element-plus'
import {
  Document,
  VideoCamera,
  Star,
  View,
  Warning,
  InfoFilled,
  ArrowRight
} from '@element-plus/icons-vue'
import { getPersonalStats, getTodoList, getRecommendJobs } from '@/api/personal'
import { getUserApplications } from '@/api/application'

const router = useRouter()

// 统计数据
const stats = ref({
  applications: 0,
  favorites: 0,
  views: 0
})

// 待办事项
const todos = ref([])

// 推荐职位
const recommendJobs = ref([])

// 加载状态
const loading = ref({
  stats: false,
  todos: false,
  jobs: false
})

// 获取活动类型对应的颜色
const getActivityColor = (type) => {
  const colorMap = {
    'primary': '#409EFF',
    'success': '#67C23A',
    'warning': '#E6A23C',
    'danger': '#F56C6C',
    'info': '#909399'
  }
  return colorMap[type] || colorMap.info
}

// 处理待办事项操作
const handleTodoAction = (todo) => {
  if (todo.type === 'resume') {
    router.push('/resumes')
  } else if (todo.type === 'job') {
    router.push('/jobs')
  } else if (todo.type === 'application') {
    router.push('/personal?tab=applications')
  } else if (todo.type === 'favorite') {
    router.push('/personal?tab=favorites')
  } else {
    // 默认行为
    router.push(todo.url || '/')
  }
}

// 查看职位详情
const viewJobDetail = (jobId) => {
  router.push(`/jobs/${jobId}`)
}

// 前往职位列表
const goToJobList = () => {
  router.push('/jobs')
}

// 获取统计数据
const fetchStats = async () => {
  try {
    loading.value.stats = true
    const res = await getPersonalStats()
    if (res && res.code === 200) {
      stats.value = res.data
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  } finally {
    loading.value.stats = false
  }
}

// 获取待办事项
const fetchTodos = async () => {
  try {
    loading.value.todos = true
    const res = await getTodoList()
    if (res && res.code === 200) {
      todos.value = res.data.map(item => ({
        ...item,
        actionText: item.actionText || '查看详情'
      }))
    }
  } catch (error) {
    console.error('获取待办事项失败:', error)
    ElMessage.error('获取待办事项失败')
  } finally {
    loading.value.todos = false
  }
}

// 获取推荐职位
const fetchRecommendJobs = async () => {
  try {
    loading.value.jobs = true
    const res = await getRecommendJobs({ limit: 3 })
    
    // 检查响应格式
    if (!res) {
      throw new Error('获取推荐职位失败: 无响应数据')
    }
    
    if (res.code !== 200) {
      throw new Error(res.message || '获取推荐职位失败')
    }
    
    // 检查data是否存在
    if (!res.data) {
      console.warn('推荐职位数据为空')
      recommendJobs.value = []
      return
    }
    
    // 处理分页数据结构
    const jobList = Array.isArray(res.data) ? res.data : (res.data.list || res.data.records || [])
    
    // 处理tags字段，确保它是数组，并限制数量为3个
    recommendJobs.value = jobList
      .slice(0, 3) // 确保最多只取3个职位
      .map(job => ({
        ...job,
        tags: job.tags ? job.tags.split(',').map(tag => tag.trim()).filter(Boolean) : []
      }))
  } catch (error) {
    console.error('获取推荐职位失败:', error)
    ElMessage.error(error.message || '获取推荐职位失败')
    recommendJobs.value = []
  } finally {
    loading.value.jobs = false
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  
  const date = new Date(dateString)
  const now = new Date()
  const diff = now - date
  
  // 一小时内
  if (diff < 3600000) {
    const minutes = Math.floor(diff / 60000)
    return `${minutes}分钟前`
  }
  
  // 24小时内
  if (diff < 86400000) {
    const hours = Math.floor(diff / 3600000)
    return `${hours}小时前`
  }
  
  // 7天内
  if (diff < 604800000) {
    const days = Math.floor(diff / 86400000)
    return `${days}天前`
  }
  
  // 超过7天显示具体日期
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 获取所有数据
const fetchData = async () => {
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '加载数据中...',
    background: 'rgba(255, 255, 255, 0.7)'
  })
  
  try {
    await Promise.all([
      fetchStats(),
      fetchTodos(),
      fetchRecommendJobs()
    ])
  } finally {
    loadingInstance.close()
  }
}

// 初始化
onMounted(() => {
  fetchData()
})
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables.css';

.personal-overview {
  .stat-cards {
    margin-bottom: var(--spacing-xl);
    
    .stat-card {
      background-color: #fff;
      border-radius: var(--border-radius);
      padding: var(--spacing-lg);
      display: flex;
      align-items: center;
      box-shadow: var(--box-shadow-sm);
      transition: all 0.3s;
      height: 100px;
      
      &:hover {
        transform: translateY(-5px);
        box-shadow: var(--box-shadow-md);
      }
      
      .stat-icon {
        width: 60px;
        height: 60px;
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: var(--spacing-md);
        
        .el-icon {
          font-size: 28px;
          color: #fff;
        }
        
        &.applications {
          background: linear-gradient(135deg, #3b82f6, #1d4ed8);
        }
        
        &.favorites {
          background: linear-gradient(135deg, #f59e0b, #d97706);
        }
        
        &.views {
          background: linear-gradient(135deg, #10b981, #047857);
        }
      }
      
      .stat-info {
        .stat-value {
          font-size: 1.8rem;
          font-weight: 600;
          color: var(--text-primary);
          margin-bottom: 2px;
          line-height: 1;
        }
        
        .stat-label {
          color: var(--text-secondary);
          font-size: 0.9rem;
        }
      }
    }
  }
  
  .section {
    margin-bottom: var(--spacing-xl);
    
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: var(--spacing-md);
      
      .section-title {
        font-size: 1.2rem;
        font-weight: 600;
        color: var(--text-primary);
        margin: 0;
        
        &::before {
          content: "";
          display: inline-block;
          width: 4px;
          height: 16px;
          background-color: var(--color-primary);
          margin-right: 8px;
          vertical-align: middle;
          border-radius: 2px;
        }
      }
    }
  }
  
  .todo-card {
    .todo-list {
      .todo-item {
        display: flex;
        align-items: center;
        padding: var(--spacing-md) 0;
        border-bottom: 1px solid var(--border-color-light);
        
        &:last-child {
          border-bottom: none;
        }
        
        &.is-urgent {
          .todo-icon {
            background-color: var(--color-danger-lighter);
            
            .el-icon {
              color: var(--color-danger);
            }
          }
          
          .todo-title {
            color: var(--color-danger);
          }
        }
        
        .todo-icon {
          width: 40px;
          height: 40px;
          border-radius: 8px;
          background-color: var(--color-primary-lighter);
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: var(--spacing-md);
          flex-shrink: 0;
          
          .el-icon {
            font-size: 20px;
            color: var(--color-primary);
          }
        }
        
        .todo-content {
          flex-grow: 1;
          
          .todo-title {
            font-weight: 500;
            color: var(--text-primary);
            margin-bottom: 4px;
          }
          
          .todo-time {
            font-size: 0.85rem;
            color: var(--text-secondary);
          }
        }
        
        .todo-action {
          margin-left: var(--spacing-md);
        }
      }
    }
  }
  
  .job-card {
    margin-bottom: var(--spacing-md);
    cursor: pointer;
    transition: all 0.3s;
    
    &:hover {
      transform: translateY(-5px);
    }
    
    .job-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: var(--spacing-sm);
      
      .job-title {
        font-weight: 600;
        color: var(--text-primary);
        font-size: 1.1rem;
        flex: 1;
      }
      
      .job-salary {
        color: var(--color-success);
        font-weight: 600;
        white-space: nowrap;
        margin-left: var(--spacing-sm);
      }
    }
    
    .job-company {
      color: var(--text-secondary);
      margin-bottom: var(--spacing-sm);
      font-size: 0.9rem;
    }
    
    .job-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      margin-bottom: var(--spacing-md);
      min-height: 24px;
      
      .el-tag {
        background-color: var(--bg-light);
        border: none;
      }
    }
    
    .job-footer {
      display: flex;
      justify-content: space-between;
      font-size: 0.85rem;
      color: var(--text-secondary);
    }
  }
}

// 响应式适配
@media (max-width: 768px) {
  .personal-overview {
    .stat-cards {
      .el-col {
        margin-bottom: var(--spacing-md);
      }
    }
    
    .job-card {
      .job-header {
        flex-direction: column;
        
        .job-salary {
          margin-left: 0;
          margin-top: 4px;
        }
      }
    }
  }
}
</style> 